<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="个人信息管理页面 - 跑单评价系统">
    <title>个人信息 - 跑单评价系统</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        /* 简化的基础样式 */
        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 0;
        }
        
        /* 导航栏样式 */
        .navbar {
            background-color: #4361ee;
            color: white;
            padding: 1rem;
            margin-bottom: 2rem;
        }
        
        .navbar-brand {
            color: white;
            font-weight: bold;
            font-size: 1.2rem;
        }
        
        .navbar-nav .nav-link {
            color: white;
            margin: 0 0.5rem;
        }
        
        /* 主内容区 */
        .container {
            max-width: 800px;
            margin-top: 2rem;
            margin-bottom: 2rem;
        }
        
        /* 卡片样式 */
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid #ddd;
            margin-bottom: 2rem;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #eee;
            font-weight: bold;
            font-size: 1.2rem;
            padding: 1rem;
        }
        
        .card-body {
            padding: 2rem;
        }
        
        /* 头像上传区域 */
        .avatar-section {
            text-align: center;
            margin-bottom: 2.5rem;
            position: relative;
        }
        
        .avatar-container {
            position: relative;
            width: 160px;
            height: 160px;
            margin: 0 auto 1rem;
            cursor: pointer;
        }
        
        .avatar-preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .avatar-container:hover .avatar-preview {
            transform: scale(1.03);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
        }
        
        .avatar-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.3s ease;
        }
        
        .avatar-container:hover .avatar-overlay {
            opacity: 1;
        }
        
        .avatar-upload-btn {
            background-color: white;
            color: #4361ee;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            transform: scale(0.9);
        }
        
        .avatar-container:hover .avatar-upload-btn {
            transform: scale(1);
        }
        
        .avatar-upload-btn:hover {
            background-color: #4361ee;
            color: white;
            transform: scale(1.1);
        }
        
        .avatar-upload-btn i {
            font-size: 1.2rem;
        }
        
        .avatar-upload-input {
            display: none;
        }
        
        .avatar-hint {
            color: #6c757d;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-label {
            font-weight: 500;
            color: #333;
            margin-bottom: 0.5rem;
            display: block;
            font-size: 0.95rem;
        }
        
        .form-control {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            width: 100%;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #4361ee;
            box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
        }
        
        .form-control:disabled {
            background-color: #f5f5f5;
            color: #6c757d;
            border-color: #ddd;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 4px;
            font-weight: 500;
            font-size: 1rem;
            border: none;
            cursor: pointer;
        }
        
        .btn-primary {
            background-color: #4361ee;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #3a0ca3;
        }
        
        .btn-secondary {
            background-color: #f8f9fa;
            color: #6c757d;
            border: 1px solid #ddd;
        }
        
        .btn-secondary:hover {
            background-color: #e9ecef;
        }
        
        .btn-secondary:hover {
            background-color: #e9ecef;
            color: #333;
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        /* 消息提示样式 */
        .alert {
            margin-top: 1.5rem;
            border-radius: 8px;
            border: none;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            padding: 1rem;
            font-size: 0.95rem;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .alert-success {
            background-color: #f0f9ff;
            color: #03548c;
            border-left: 4px solid #4cc9f0;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .alert-danger {
            background-color: #fff0f0;
            color: #8c0327;
            border-left: 4px solid #f72585;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .alert-info {
            background-color: #f0f8ff;
            color: #03548c;
            border-left: 4px solid #4cc9f0;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin-top: 1.5rem;
                margin-bottom: 1.5rem;
                padding: 0 1rem;
            }
            
            .card-body {
                padding: 1.5rem;
            }
            
            .avatar-container {
                width: 120px;
                height: 120px;
            }
            
            .navbar-brand {
                font-size: 1.1rem;
            }
            
            .btn {
                width: 100%;
                margin-bottom: 0.5rem;
            }
            
            .btn:last-child {
                margin-bottom: 0;
            }
        }
        
        /* 加载动画 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/reviews">
                <i class="fa fa-star mr-2"></i>跑单评价系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/reviews">
                            <i class="fa fa-list-alt mr-1"></i>评价列表
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" aria-current="page" href="/profile">
                            <i class="fa fa-user-circle mr-1"></i>个人信息
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/logout">
                            <i class="fa fa-sign-out mr-1"></i>退出登录
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="card">
            <div class="card-header">
                <i class="fa fa-user-circle-o mr-2"></i>个人信息管理
            </div>
            <div class="card-body">
                <!-- 消息提示区域 -->
                <div id="message" class="alert d-none" role="alert"></div>

                <!-- 头像上传区域 -->
                <div class="avatar-section">
                    <div class="avatar-container" onclick="document.getElementById('avatarUpload').click()">
                        <img id="avatarPreview" src="" alt="用户头像" class="avatar-preview">
                        <div class="avatar-overlay">
                            <button type="button" class="avatar-upload-btn" title="更换头像">
                                <i class="fa fa-camera"></i>
                            </button>
                        </div>
                    </div>
                    <input type="file" id="avatarUpload" accept="image/*" class="avatar-upload-input">
                    <p class="avatar-hint">点击头像更换</p>
                </div>

                <!-- 个人信息表单 -->
                <form id="profileForm">
                    <div class="form-group">
                        <label for="username" class="form-label"><i class="fa fa-id-card-o mr-1"></i>用户名</label>
                        <input type="text" class="form-control" id="username" disabled placeholder="用户名不可修改">
                    </div>
                    
                    <div class="form-group">
                        <label for="nickname" class="form-label"><i class="fa fa-user-o mr-1"></i>昵称</label>
                        <input type="text" class="form-control" id="nickname" name="nickname" placeholder="请输入您的昵称">
                    </div>
                    
                    <div class="form-group">
                        <label for="email" class="form-label"><i class="fa fa-envelope-o mr-1"></i>邮箱</label>
                        <input type="email" class="form-control" id="email" name="email" placeholder="请输入您的邮箱地址">
                    </div>
                    
                    <div class="form-group">
                        <label for="phone" class="form-label"><i class="fa fa-phone mr-1"></i>手机号</label>
                        <input type="tel" class="form-control" id="phone" name="phone" placeholder="请输入您的手机号码">
                    </div>

                    <div class="form-group">
                        <label for="createdTime" class="form-label"><i class="fa fa-calendar-plus-o mr-1"></i>注册时间</label>
                        <input type="text" class="form-control" id="createdTime" disabled>
                    </div>

                    <div class="form-group">
                        <label for="updatedTime" class="form-label"><i class="fa fa-calendar-check-o mr-1"></i>最后更新时间</label>
                        <input type="text" class="form-control" id="updatedTime" disabled>
                    </div>

                    <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                        <button type="button" class="btn btn-secondary mr-md-2" id="resetBtn">
                            <i class="fa fa-refresh mr-1"></i>重置
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fa fa-save mr-1"></i>保存修改
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 获取CSRF令牌
        function getCSRFToken() {
            const tokenElement = document.querySelector('meta[name="_csrf"]');
            return tokenElement ? tokenElement.getAttribute('content') : '';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = message;
            messageDiv.className = `alert alert-${type} mt-3`;
            messageDiv.classList.remove('d-none');
            
            // 3秒后隐藏消息，添加淡出动画
            setTimeout(() => {
                messageDiv.style.transition = 'opacity 0.3s ease-out';
                messageDiv.style.opacity = '0';
                setTimeout(() => {
                    messageDiv.classList.add('d-none');
                    messageDiv.style.opacity = '1'; // 重置透明度
                }, 300);
            }, 3000);
        }

        // 加载用户信息
        function loadUserInfo() {
            console.log('开始加载用户信息');
            const token = getCookie('jwtToken');
            console.log('使用Token:', token ? '已获取token' : '未获取到token');
            
            // 使用更简单的fetch API替代jQuery ajax
            fetch('/api/user/profile', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token ? `Bearer ${token}` : ''
                }
            })
            .then(response => {
                console.log('API响应状态:', response.status);
                if (!response.ok) {
                    throw new Error('API请求失败: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log('获取到的用户数据:', data);
                if (data.success && data.data) {
                    const userData = data.data;
                    
                    // 添加淡入动画效果
                    const formFields = ['username', 'nickname', 'email', 'phone', 'createdTime', 'updatedTime'];
                    formFields.forEach(field => {
                        const element = document.getElementById(field);
                        element.style.opacity = '0';
                        setTimeout(() => {
                            element.value = field === 'createdTime' || field === 'updatedTime' 
                                ? formatDate(userData[field]) 
                                : (userData[field] || '');
                            element.style.transition = 'opacity 0.3s ease-in';
                            element.style.opacity = '1';
                        }, 100 * formFields.indexOf(field));
                    });
                    
                    // 设置头像，添加加载动画
                    const avatarPreview = document.getElementById('avatarPreview');
                    avatarPreview.style.opacity = '0.6';
                    
                    // 构建正确的头像URL
                    let avatarUrl;
                    if (userData.avatar && userData.avatar.startsWith('http')) {
                        avatarUrl = userData.avatar;
                    } else if (userData.avatar) {
                        // 直接使用'/file/' + 文件名访问
                        avatarUrl = '/file/' + userData.avatar;
                        console.log('构建头像URL:', avatarUrl);
                    } else {
                        avatarUrl = '/file/default-avatar.png';
                    }
                    
                    const img = new Image();
                    img.onload = function() {
                        avatarPreview.src = avatarUrl;
                        avatarPreview.style.transition = 'opacity 0.3s ease-in';
                        avatarPreview.style.opacity = '1';
                    };
                    img.onerror = function() {
                        // 加载失败时使用默认头像
                        avatarPreview.src = '/file/default-avatar.png';
                        avatarPreview.style.transition = 'opacity 0.3s ease-in';
                        avatarPreview.style.opacity = '1';
                    };
                    img.src = avatarUrl;
                } else {
                    showMessage('获取用户信息失败: ' + (data.message || '未知错误'), 'danger');
                }
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
                showMessage('获取用户信息失败，请刷新页面重试', 'danger');
            });
        }

        // 获取Cookie
        function getCookie(name) {
            // 添加调试日志
            console.log('获取Cookie:', name);
            console.log('当前Cookie:', document.cookie);
            
            const cookieValue = document.cookie
                .split('; ')
                .find(row => row.startsWith(name + '='))
                ?.split('=')[1];
            const result = cookieValue ? decodeURIComponent(cookieValue) : '';
            console.log('获取到的Cookie值:', result);
            return result;
        }

        // 表单验证
        function validateForm() {
            const email = document.getElementById('email').value;
            const phone = document.getElementById('phone').value;
            
            // 简单的邮箱验证
            if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                showMessage('请输入有效的邮箱地址', 'danger');
                return false;
            }
            
            // 简单的手机号验证（中国大陆手机号）
            if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
                showMessage('请输入有效的手机号码', 'danger');
                return false;
            }
            
            return true;
        }

        // 头像上传
document.getElementById('avatarUpload').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            console.log('选择的文件:', file.name, file.size, file.type);

            // 验证文件类型
            if (!file.type.match('image.*')) {
                showMessage('请上传图片文件', 'danger');
                return;
            }

            // 验证文件大小（1MB限制）
            if (file.size > 1024 * 1024) {
                showMessage('文件大小不能超过1MB', 'danger');
                return;
            }

            // 显示加载提示
            showMessage('<div class="loading mr-2"></div> 正在上传头像...', 'info');

            const formData = new FormData();
            formData.append('file', file);
            console.log('表单数据已准备');

            // 临时预览上传的图片
            const reader = new FileReader();
            reader.onload = function(e) {
                const avatarPreview = document.getElementById('avatarPreview');
                avatarPreview.style.opacity = '0.7';
                avatarPreview.src = e.target.result;
                avatarPreview.style.transition = 'opacity 0.3s ease-in';
                setTimeout(() => {
                    avatarPreview.style.opacity = '1';
                }, 300);
            };
            reader.readAsDataURL(file);

            const token = getCookie('jwtToken');
            console.log('上传头像使用Token:', token ? '已获取token' : '未获取到token');

            // 使用fetch API替代jQuery ajax
            fetch('/api/user/avatar', {
                method: 'POST',
                body: formData,
                headers: {
                    // 添加Authorization头部用于认证
                    'Authorization': token ? `Bearer ${token}` : ''
                }
            })
            .then(response => {
                console.log('头像上传API响应状态:', response.status, response.statusText);
                
                // 尝试获取响应文本，无论成功或失败
                return Promise.all([response.ok, response.text()]);
            })
            .then(([ok, text]) => {
                console.log('头像上传响应内容:', text);
                
                let data;
                try {
                    data = JSON.parse(text);
                } catch (e) {
                    console.error('JSON解析错误:', e);
                    data = { success: false, message: '无效的响应格式' };
                }
                
                if (ok && data.success) {
                    // 更新头像预览，添加成功动画
                    const avatarPreview = document.getElementById('avatarPreview');
                    avatarPreview.style.transform = 'scale(1.1)';
                    setTimeout(() => {
                        avatarPreview.style.transition = 'transform 0.3s ease-out';
                        avatarPreview.style.transform = 'scale(1)';
                    }, 150);
                    showMessage('<i class="fa fa-check-circle mr-2"></i> 头像上传成功', 'success');
                } else {
                    // 恢复原始头像
                    loadUserInfo();
                    showMessage('头像上传失败: ' + (data.message || '未知错误'), 'danger');
                }
            })
            .catch(error => {
                console.error('头像上传失败:', error);
                // 恢复原始头像
                loadUserInfo();
                showMessage('头像上传失败，请重试: ' + error.message, 'danger');
            });
        });

        // 表单提交
        document.getElementById('profileForm').addEventListener('submit', function(e) {
            e.preventDefault();

            // 表单验证
            if (!validateForm()) {
                return;
            }

            const userData = {
                nickname: document.getElementById('nickname').value.trim(),
                email: document.getElementById('email').value.trim(),
                phone: document.getElementById('phone').value.trim()
            };

            showMessage('<div class="loading mr-2"></div> 正在保存修改...', 'info');

            // 为表单添加加载状态
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<div class="loading"></div> 保存中...';

            const token = getCookie('jwtToken');
            console.log('保存用户信息使用Token:', token ? '已获取token' : '未获取到token');

            // 使用fetch API替代jQuery ajax
            fetch('/api/user/profile', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token ? `Bearer ${token}` : ''
                },
                body: JSON.stringify(userData)
            })
            .then(response => {
                console.log('保存用户信息API响应状态:', response.status);
                if (!response.ok) {
                    throw new Error('保存用户信息请求失败: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log('保存用户信息响应数据:', data);
                if (data.success) {
                    showMessage('<i class="fa fa-check-circle mr-2"></i> 个人信息更新成功', 'success');
                    // 更新更新时间显示
                    if (data.data && data.data.updatedTime) {
                        const updatedTime = document.getElementById('updatedTime');
                        updatedTime.style.opacity = '0';
                        setTimeout(() => {
                            updatedTime.value = formatDate(data.data.updatedTime);
                            updatedTime.style.transition = 'opacity 0.3s ease-in';
                            updatedTime.style.opacity = '1';
                        }, 300);
                    }
                } else {
                    showMessage('更新失败: ' + (data.message || '未知错误'), 'danger');
                }
            })
            .catch(error => {
                console.error('更新失败:', error);
                showMessage('更新失败，请重试', 'danger');
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });

        // 重置按钮
        document.getElementById('resetBtn').addEventListener('click', function() {
            // 添加确认提示
            if (confirm('确定要重置为当前保存的信息吗？未保存的修改将会丢失。')) {
                // 为按钮添加加载状态
                const originalText = this.innerHTML;
                this.disabled = true;
                this.innerHTML = '<div class="loading"></div> 重置中...';
                
                setTimeout(() => {
                    loadUserInfo(); // 重新加载用户信息
                    showMessage('<i class="fa fa-refresh mr-2"></i> 信息已重置', 'info');
                    // 恢复按钮状态
                    this.disabled = false;
                    this.innerHTML = originalText;
                }, 500);
            }
        });

        // 平滑滚动
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                document.querySelector(this.getAttribute('href')).scrollIntoView({
                    behavior: 'smooth'
                });
            });
        });

        // 页面加载完成后加载用户信息
        document.addEventListener('DOMContentLoaded', function() {
            // 添加页面载入动画
            document.body.style.opacity = '0';
            document.body.style.transition = 'opacity 0.5s ease-in';
            setTimeout(() => {
                document.body.style.opacity = '1';
                loadUserInfo();
            }, 200);
        });
    </script>
</body>
</html>